<?php

namespace App\Http\Service\Impl;

use App\Http\Service\IIndex;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use phpDocumentor\Reflection\Types\Array_;
use function foo\func;

class IndexImpl implements IIndex
{

    function gettree($request)
    {
        // TODO: Implement gettree() method.
        //$mgid = Session::get("mgid");
        $auth_menu = DB::select("SELECT mg.*,ar.ar_id,au.auth_id id,au.auth_pid pid,
                                 au.auth_name text,au.auth_level level,
                                 au.auth_path href
                                 FROM zhyl_sys_mgrole mg,zhyl_sys_authrole ar,zhyl_sys_auth au WHERE mg_id =?
                                 AND mg.role_id=ar.role_id AND au.`status`=1
                                 AND ar.auth_id = au.auth_id
                                 GROUP BY au.auth_id order by ifnull(sn,999)", [Session::get("mgid")]);
        $resortdata = authtree($auth_menu);
        foreach ($resortdata as $k => $v) {
            $resortdata[$k]['state'] = has_child($v['id']) ? 'closed' : 'open';
        }
        $listdata = \PHPTree::makeTree($resortdata);
        return $listdata;
    }

    function userlist($request)
    {
        // TODO: Implement userlist() method.
        $where = " where 1=1 ";
        if ($request->dhmc) {
            $where .=  " and mg_code like '%$request->dhmc%'";
        }
        if ($request->yhmc) {
            $where .=  " and mg_name like '%$request->yhmc%'";
        }
        if ($request->roleid) {
            $ids    = DB::table("mgrole")
                ->where("role_id", $request->roleid)
                ->select("mg_id")
                ->get()
                ->reduce(function ($res, $item) {
                    $res[] = $item->mg_id;
                    return $res;
                });
            $idsstr = implode_arrs($ids);
            $where .=  " and mg_id in ({$idsstr})";
        }
        if ($request->yxbz != "" && $request->yxbz != null) {
            $where .=  " and mg_status = $request->yxbz";
        }
        $list  = DB::select(
            "SELECT GROUP_CONCAT(r.role_name) jsmc ,t2.* from (
                             SELECT mg.role_id rids,t.* from (
                             SELECT m.*,
                             CASE m.mg_status
                             WHEN 1 THEN '正常' ELSE '禁用' END zt
                             FROM zhyl_sys_manager m LIMIT ?,?
                             )t,zhyl_sys_mgrole mg where t.mg_id=mg.mg_id ORDER BY t.mg_name
                             ) t2 left join zhyl_sys_role r on t2.rids = r.role_id" . $where . " GROUP BY t2.mg_name ",
            [$request->rows * ($request->page - 1), $request->rows]
        );
        $total = DB::select("SELECT count(*) c from (
                             SELECT mg.role_id rids,t.* from (
                             SELECT m.*,
                             CASE m.mg_status
                             WHEN 1 THEN '正常' ELSE '禁用' END zt
                             FROM zhyl_sys_manager m
                             )t,zhyl_sys_mgrole mg where t.mg_id=mg.mg_id ORDER BY t.mg_name
                             ) t2 left join zhyl_sys_role r on t2.rids = r.role_id" . $where);
        $res = array("rows" => $list, "total" => $total[0]->c);
        return $res;
    }

    /**
     * @return array
     * 返回所有的角色列表(包含但不限于当前账号拥有的)
     */
    function rolelist()
    {
        // TODO: Implement rolelist() method.
        return DB::select("select * from zhyl_sys_role");
    }


    function rolebtnlist()
    {
        return DB::table("rule")->get();
    }

    function getrolebtnlist($request)
    {
        // TODO: Implement getrolebtnlist() method.
        $rules   = DB::table("rule")->get();
        $myrules = DB::table("role")->where("role_id", 2)->get();
        foreach ($rules as $k => $v) {
            $data = array(
                "id"    => $v->id,
                "name"  => $v->name,
                "title" => $v->title,
                "flag"  => in_array($v->id, $myrules) ? 'true' : 'false'
            );

            $response['rows'][] = $data;
            $response['total'] = 50;
        }



        return $response;
    }


    function editor_detail($request)
    {
        // TODO: Implement editor_detail() method.
        $rlist = DB::table("role")->select("role_name", "role_id")->get();
        $info  = DB::table("manager")->where("mg_id", $request->mg_id)->get();
        $hava  = DB::table("mgrole")->where("mg_id", $request->mg_id)->select("role_id")->get()->reduce(function ($res, $item) {
            $res[] = $item->role_id;
            return $res;
        });
        $res = array("rolelist" => $rlist, "info" => $info, "have" => $hava);
        //p($res);
        //die;
        return $res;
    }

    function updaterole($request)
    {
        // TODO: Implement updaterole() method.
        DB::transaction(function () use ($request) {
            //更新用户信息
            $info = DB::update(
                "update zhyl_sys_manager set mg_code=?,mg_name=? where mg_id=?",
                [$request->mg_code, $request->mg_name, $request->mg_id]
            );
            //删除用户角色表的数据
            DB::delete("delete from zhyl_sys_mgrole where mg_id=?", [$request->mg_id]);
            $ids = collect($request->rids)->reduce(function ($res, $item) use ($request) {
                $res[] = array("role_id" => $item, "mg_id" => $request->mg_id);
                return $res;
            });
            //重新插入用户角色
            DB::table("mgrole")->insert($ids);
        });
        return returnMsg();
    }

    function addrole($request)
    {
        // TODO: Implement addrole() method.
        DB::transaction(function () use ($request) {
            //新增角色并返回角色id
            DB::table("role")->insert(array("role_name" => $request->role_name, "role_code" => $request->role_code));
            //利用角色id捆绑角色权限
            $lastid = DB::getPdo()->lastInsertId();
            $authrole = collect($request->auth)->reduce(function ($res, $item) use ($lastid) {
                $res[] = array("role_id" => $lastid, "auth_id" => $item);
                DB::table("authrole")->insert($res);
            });
        });
    }

    /**
     * @param $request
     * 根据点选的角色获取权限
     */
    function getauth($request)
    {
        // TODO: Implement getauth() method.
        $auth_menu = DB::select("SELECT au.auth_id id,au.auth_pid pid,
                                 au.auth_name text,au.auth_level level,
                                 au.auth_path href
                                 FROM zhyl_sys_auth au
                                 GROUP BY au.auth_id");
        $resortdata = authtree($auth_menu);
        $auth_ids = DB::table("authrole")->where("role_id", $request->role_id)->get()->reduce(function ($res, $item) {
            $res[] = $item->auth_id;
            return $res;
        });
        foreach ($resortdata as $k => $v) {
            $v[$k]['state'] = has_child($v['id']) ? 'closed' : 'open';
            if (in_array($v['id'], $auth_ids) && $v["pid"] != 0 && $v["pid"] != 187) {
                $resortdata[$k]['checked'] = true;
            } else {
                $resortdata[$k]['checked'] = false;
            }
        }
        return \PHPTree::makeTree($resortdata);
    }

    function addroleauth($request)
    {
        // TODO: Implement addroleauth() method.
        $auth_ids = collect($request->auth_ids)->reduce(function ($res, $item) use ($request) {
            $res[] = array("role_id" => $request->role_id, "auth_id" => $item);
            return $res;
        });
        DB::table("authrole")->where("role_id", $request->role_id)->delete();
        DB::table("authrole")->insert($auth_ids);
        return "true";
    }

    function addmanager($request)
    {
        // TODO: Implement addmanager() method.
        DB::transaction(function () use ($request) {
            //新增角色并返回角色id
            $info = array("mg_code" => $request->mg_code, "mg_pwd" => md5($request->mg_pwd), "mg_name" => $request->mg_name, "phone" => $request->phone);
            DB::table("manager")->insert($info);
            //获取插入的用户id,并且用户id捆绑角色
            $lastid = DB::getPdo()->lastInsertId();
            $authrole = collect($request->rids)->reduce(function ($res, $item) use ($lastid) {
                $res[] = array("mg_id" => $lastid, "role_id" => $item);
                DB::table("mgrole")->insert($res);
            });
        });
    }

    function deletemanager($request)
    {
        // TODO: Implement deletemanager() method.
        DB::transaction(function () use ($request) {
            DB::table("manager")->where("mg_id", $request->mg_id)->delete();
            DB::table("mgrole")->where("mg_id", $request->mg_id)->delete();
        });
        return "true";
    }
}
